package util.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SMTHParser extends AbstractParser {
	public static Pattern authorPattern = Pattern.compile("^发信人: (.*) \\((.*)\\), 信区: (.*)$");
	public static Pattern titlePattern = Pattern.compile("^标  题: (.*)$");
	public static Pattern sitePattern = Pattern.compile("^发信站: ([.])$");
	public static Pattern ignorePattern = Pattern.compile("^(: .*|【.*】)$");
	
	/**
	 * 当val是NULL的时候返回def
	 * @param val
	 * @param def
	 * @return
	 */
	private String NullValue(String val, String def) {
		return val == null ? def : val;
	}
	
	@Override
	public Map<String, String> getFileProperty(File file) {
		Map<String, String> property = new HashMap<String, String>();
		property.put(FILE_SIZE_KEY, "" + (file.length() / 1024) + "K");
		BufferedReader br;
		try {
			br = new BufferedReader(
					new InputStreamReader(new FileInputStream(file), "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line;
			Matcher matcher;
			line = br.readLine();
			matcher = authorPattern.matcher(line);
			if (matcher.matches()) {
				property.put(AUTHOR_KEY, NullValue(matcher.group(1), "NULL"));
				property.put(AUTHOR_NICK_KEY, NullValue(matcher.group(2), "NULL"));
				property.put(BOARD_KEY, NullValue(matcher.group(3), "NULL"));
			} else {
				property.put(AUTHOR_KEY, "PARSE_ERROR");
				property.put(AUTHOR_NICK_KEY, "PARSE_ERROR");
				property.put(BOARD_KEY, "PARSE_ERROR");
			}
			line = br.readLine();
			matcher = titlePattern.matcher(line);
			if (matcher.matches()) {
				property.put(TITLE_KEY, NullValue(matcher.group(1), "NULL"));
			} else {
				property.put(TITLE_KEY, "PARSE_ERROR");
			}
			line = br.readLine();
			matcher = sitePattern.matcher(line);
			if (matcher.matches()) {
				property.put(SITE_KEY, NullValue(matcher.group(1), "NULL"));
			} else {
				property.put(SITE_KEY, "PARSE_ERROR");
			}
			
			while ((line = br.readLine()) != null) {
				matcher = ignorePattern.matcher(line);
				if (!matcher.matches()) {
					sb.append(line);
					sb.append('\n');
				}
			}
			br.close();
			property.put(IParser.CONTENT_KEY, sb.toString());
		} catch (FileNotFoundException e) {
			System.err.println("File " + file.getName() + " not found!");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Error opening file " + file.getName());
			e.printStackTrace();
		}
		return property;
	}

}
